package home.fragment;

import static android.content.ContentValues.TAG;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.fragment.app.FragmentManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shoppapp.R;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import app.RegisterActivity;
import app.SearchActivity;
import base.BaseFragment;
import home.HttpUrlConnectionClient;
import home.JsonParser;
import home.bean.Carousel;
import home.bean.Data;
import home.bean.Goods;
import home.bean.ApiResponse;
import okhttp3.Call;
import utils.Constants;

/*主页面的Fragment*/
public class HomeFragment extends BaseFragment implements HttpUrlConnectionClient.OnDataFetchedListener{
    @Override
    public View initView() {
        View view=View.inflate(mcontext, R.layout.fragment_home,null);
        return view;
    }
    public void initData(){
        super.initData();
        //联网请求主页的数据
        getDataFromNet();




    }
    private void getDataFromNet(){
        String url= Constants.Home_URL;
        OkHttpUtils
                .get()
                .url(url)
                //.addParams("username","13938246724")
                //.addParams("password","123456")
                .build()
                .execute(new StringCallback() {
                    //当请求失败的时候回调
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e(TAG,"首页请求失败=="+e.getMessage());
                    }

                    //当请求成功的时候回调
                    //response 请求成功的数据
                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG,"首页请求成功=="+response);
                        //解析数据
                        processData(response);


                    }
                });
    }
    private void processData(String json){
        // 初始化网络客户端
        HttpUrlConnectionClient client = new HttpUrlConnectionClient( this);
        String apiUrl = "http://115.158.64.84:28019/api/v1/index-infos"; // 替换为实际 API 地址
        client.fetchData(apiUrl);
    }
    // 网络请求成功回调
    @Override
    public void onSuccess(String json) {
        try {
            // 解析 JSON 数据
            ApiResponse apiResponse = JsonParser.parse(json);
            // 处理数据（示例：打印商品名称）
            if (!apiResponse.getData().getHotGoodses().isEmpty()) {
                String firstGoodsName = apiResponse.getData().getHotGoodses().get(0).getGoodsName();
                showToast("获取成功：" + firstGoodsName);
            }
        } catch (JSONException e) {
            e
                    .printStackTrace();
            showToast("数据解析失败");
        }
    }

    // 网络请求失败回调
    @Override
    public void onFailure(String message) {
        showToast("失败：" + message);
    }

    // 显示 Toast（主线程）
    private void showToast(String message) {
        if (getView() != null) { // 确保 View 存在
            getView().post(() -> {
                Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
            });
        }
    }














    //    // TODO: Rename parameter arguments, choose names that match
//    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//    private static final String ARG_PARAM1 = "param1";
//    private static final String ARG_PARAM2 = "param2";
//
//    // TODO: Rename and change types of parameters
//    private String mParam1;
//    private String mParam2;
//
//    public HomeFragment() {
//        // Required empty public constructor
//    }
//
//    /**
//     * Use this factory method to create a new instance of
//     * this fragment using the provided parameters.
//     *
//     * @param param1 Parameter 1.
//     * @param param2 Parameter 2.
//     * @return A new instance of fragment HomeFragment.
//     */
//    // TODO: Rename and change types and number of parameters
//    public static HomeFragment newInstance(String param1, String param2) {
//        HomeFragment fragment = new HomeFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
//        return fragment;
//    }
//
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
//        }
//    }
    private boolean isLogin=false; // 是否登录状态
    private LinearLayout hometop;  // 顶部导航栏布局
    private ImageView iv_home_left; // 左侧图标（菜单/返回）
    private TextView tv_home_login; // 登录按钮（未登录时显示）
    private TextView tv_home_search; // 搜索框
    private ImageView iv_home_login; // 用户头像（已登录时显示）
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        ScrollView sv_home=view.findViewById(R.id.sv_home);

        // 初始化视图组件
        hometop = view.findViewById(R.id.home_top);
        iv_home_left=view.findViewById(R.id.iv_home_left);
        tv_home_login=view.findViewById(R.id.tv_home_login);
        tv_home_search=view.findViewById(R.id.tv_home_search);
        iv_home_login=view.findViewById(R.id.iv_home_login);
        // 根据登录状态显示/隐藏UI元素
        if(isLogin){
            tv_home_login.setVisibility(View.GONE);
            iv_home_login.setVisibility(View.VISIBLE);
        }else{
            iv_home_login.setVisibility(View.GONE);
            tv_home_login.setVisibility(View.VISIBLE);
        }
        tv_home_login.setOnClickListener(v -> {
            Intent intent=new Intent(getContext(), RegisterActivity.class);
            startActivityForResult(intent,100);// 启动登录/注册页面，请求码为100
        });
        tv_home_search.setOnClickListener(v -> {
            Intent intent=new Intent(getContext(), SearchActivity.class);
            startActivity(intent);
        });
        //菜单的监听，跳转至分类页面的Fragment
        iv_home_left.setOnClickListener(v -> {
            FragmentManager fragmentManager = requireActivity().getSupportFragmentManager();
            fragmentManager
                    .beginTransaction()
                    .replace(R.id.fragmentContainerView, new CategoryFragment())
                    .addToBackStack(null)
                    .commit();
        });
        sv_home.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // 滚动超过200px时，导航栏变为实色背景
                if(scrollY>200){
                    hometop.setBackgroundResource(R.color.top);
                    iv_home_left.setImageResource(R.drawable.ic_menu);
                    tv_home_login.setTextColor(Color.WHITE);
                    iv_home_login.setImageResource(R.drawable.ic_person_white);
                }else {
                    // 滚动较小时，导航栏为透明背景
                    hometop.setBackgroundColor(Color.TRANSPARENT);
                    iv_home_left.setImageResource(R.drawable.ic_menu2);
                    tv_home_login.setTextColor(getResources().getColor(R. color.top));
                    iv_home_login.setImageResource(R.drawable.ic_person);
                }
            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) { // 对应登录请求码
            if (data != null) { // 添加空值检查
                int result = data.getIntExtra("result", 0);
                if (result > 0) { // 登录成功
                    isLogin = true;
                    tv_home_login.setVisibility(View.GONE);
                    iv_home_login.setVisibility(View.VISIBLE);
                }
            } else {
                // 处理data为null的情况，例如记录日志或显示错误提示
                Log.w(TAG, "onActivityResult: data is null for requestCode=" + requestCode);
            }
        }
    }
}